"""
聚合数据实时天气API实现

此模块提供了基于聚合数据的实时天气API接口，用于获取城市天气信息。
"""

import os
import json
import logging
import urllib
import urllib.request as request
import urllib.error as error
from typing import Dict, Any, Optional
from datetime import datetime
from tenacity import retry, stop_after_attempt, wait_exponential

# 设置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger("weather_api")

# 从环境变量获取API密钥
#JUHE_WEATHER_API_KEY = os.environ.get("JUHE_WEATHER_API_KEY", "YOUR_API_KEY")
JUHE_WEATHER_API_KEY = "22cfd0c97268************************232"

class WeatherApiError(Exception):
    """天气API错误的自定义异常"""
    pass

@retry(
    stop=stop_after_attempt(3),
    wait=wait_exponential(multiplier=1, min=2, max=10),
    reraise=True
)
def fetch_real_weather_data(city: str, date: Optional[str] = None) -> Dict[str, Any]:
    """
    使用聚合数据API获取指定城市的实时天气数据。
    
    参数:
        city: 要获取天气的城市名称
        date: YYYY-MM-DD格式的日期（当前版本仅支持实时天气，忽略日期参数）
    
    返回:
        包含天气信息的字典
    
    异常:
        WeatherApiError: 如果API请求失败
    """
    logger.info(f"正在获取{city}的实时天气数据")
    
    # 构建API URL和参数
    api_url = 'http://apis.juhe.cn/simpleWeather/query'
    
    params_dict = {
        "city": city,
        "key": JUHE_WEATHER_API_KEY,
    }
    
    params = urllib.parse.urlencode(params_dict)
    
    try:
        # 发送API请求
        req = request.Request(api_url, params.encode())
        response = request.urlopen(req)
        content = response.read()
        
        if not content:
            raise WeatherApiError("API请求返回空内容")
        
        # 解析JSON响应
        result = json.loads(content)
        error_code = result.get('error_code')
        
        # 检查API返回的错误码
        if error_code != 0:
            error_reason = result.get('reason', '未知错误')
            raise WeatherApiError(f"天气API错误: {error_code}, 原因: {error_reason}")
        
        # 提取并格式化天气数据
        realtime_data = result['result']['realtime']
        future_data = result['result'].get('future', [])
        
        # 准备返回数据结构
        weather_data = {
            "location": {
                "name": city,
                "country": "中国"
            },
            "realtime": {
                "temperature": realtime_data['temperature'],
                "humidity": realtime_data['humidity'],
                "info": realtime_data['info'],
                "wid": realtime_data['wid'],
                "direct": realtime_data['direct'],
                "power": realtime_data['power'],
                "aqi": realtime_data['aqi']
            },
            "forecast": []
        }
        
        # 如果有预报数据，添加到返回结果中
        if future_data:
            for day_data in future_data:
                weather_data["forecast"].append({
                    "date": day_data['date'],
                    "temperature": day_data['temperature'],
                    "weather": day_data['weather'],
                    "wind_direction": day_data['direct']
                })
        
        logger.info(f"成功获取{city}的天气数据")
        return weather_data
        
    except error.HTTPError as e:
        logger.error(f"天气API HTTP错误: {str(e)}")
        raise WeatherApiError(f"HTTP请求失败: {str(e)}")
    except error.URLError as e:
        logger.error(f"天气API URL错误: {str(e)}")
        raise WeatherApiError(f"URL请求失败: {str(e)}")
    except json.JSONDecodeError as e:
        logger.error(f"JSON解析错误: {str(e)}")
        raise WeatherApiError(f"无法解析API响应: {str(e)}")
    except Exception as e:
        logger.error(f"获取天气数据时发生意外错误: {str(e)}")
        raise WeatherApiError(f"处理天气数据时出错: {str(e)}")

def get_weather_info(city: str, date: Optional[str] = None) -> str:
    """
    获取天气信息并格式化为用户友好的字符串。
    
    参数:
        city: 要获取天气的城市
        date: 要获取天气的日期 (YYYY-MM-DD)
    
    返回:
        格式化的天气信息字符串
    """
    try:

        # 使用真实API获取数据
        weather_data = fetch_real_weather_data(city, date)
        
        # 格式化实时天气数据
        realtime = weather_data["realtime"]
        location = weather_data["location"]["name"]
        
        result = (
            f"{location} 实时天气:\n"
            f"- 天气状况: {realtime['info']}\n"
            f"- 温度: {realtime['temperature']}°C\n"
            f"- 湿度: {realtime['humidity']}%\n"
            f"- 风向: {realtime['direct']}\n"
            f"- 风力: {realtime['power']}\n"
            f"- 空气质量: {realtime['aqi']}"
        )
        
        # 如果有预报数据，添加到结果中
        if weather_data.get("forecast") and len(weather_data["forecast"]) > 0:
            future_date = weather_data["forecast"][0]
            result += f"\n\n未来天气预报 ({future_date['date']}):\n"
            result += f"- 温度: {future_date['temperature']}\n"
            result += f"- 天气: {future_date['weather']}\n"
            result += f"- 风向: {future_date['wind_direction']}"
        
        return result
    
    except WeatherApiError as e:
        return f"错误: {str(e)}"
    except Exception as e:
        logger.error(f"天气工具发生意外错误: {str(e)}")
        return f"抱歉，获取天气信息时发生意外问题: {str(e)}"

if __name__ == "__main__":
    # 简单测试
    test_city = "北京"
    print(f"测试获取{test_city}的天气信息:")
    print(get_weather_info(test_city))